
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  event;

import logger.PoolLogger;
import mail.SndMail;
import type.Receiver;
import type.Report;
import utility.CapitalChar;
import utility.Input;
import database.RecordSearch;
import dbmanager.Column;
import dbmanager.DBManager;
import dbmanager.GetIdName;
import file.SearchRecord;
import java.io.File;
import java.util.*;

import query.view.Query;


public class Sendmail extends Thread implements Event
{
	private boolean Result=false; 
	String emailid;
	String msg;
	String tid;
	String transaction_type;
	String TRANSTYPE="transaction_type";
	String REPORT="report_master";
	GetIdName gid;
	SearchRecord sr; 
	String userId;
	public Hashtable<Object, Object> Sendmail = new Hashtable<Object, Object>();
	Hashtable<Object, Object> Reportmap = new Hashtable<Object, Object>();
	public Vector<Object> RECEIVERemailid =new Vector<Object>();
	String Source;
	String attachment;
	PoolLogger pl;
	
	public Sendmail()
	{
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	 
	public static void main(String hmt[])
	{
		try
		{
			Sendmail sm = new Sendmail();
			sm.SetData("o<aa,ada10#605", "po", "9", "+919922930640");
			sm.initializationData();
			sm.setObject("");
			System.out.println("Email Id : "+sm.getUserEmail("+919922930640"));
			sm.run();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public void SetData(String msg, String transaction_type, String tid, String userid,String Source,String datetime,String request)
	{	
		this.msg =msg;
		this.transaction_type=transaction_type;
		this.tid=tid;
		this.userId = userid;
		this.Source = Source;
	}
	
	public void run() 
	{	
		
		try 
		{	
			String subject =Sendmail.get("subject").toString() + " "+ tid;
			String bodyText = Sendmail.get("bodytext").toString();
			if(REPORT.toLowerCase().equals(Source.toLowerCase()))
			{
				Report report = new Report(gid.getId(msg));
				String typeofreport = report.GettypeofReport();
				query.condition.typereport.Typereport type; 
				Class C = Class.forName("query.condition.typereport."+CapitalChar.makeFirstCharCapital(typeofreport.trim()));
				type = (query.condition.typereport.Typereport )C.newInstance();
				type.setData("",tid, Reportmap);
				String path = type.getPath(msg);
				attachment=path;
			}
			else
			{	
				SndMail send = new SndMail();
					
						try
						{	
							send.postMail("bills@osc.co.in" ,RECEIVERemailid,attachment,subject,bodyText);
						}
						catch (Exception e) 
						{
						}
					Result = true;
				}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}

	public void setObject(String eventobject) 
	{	
		//String path = Input.MASTERREPORTSPATH + eventobject + "//" +eventobject +"_mid" + Input.FILRFORMAT;
		Hashtable< Object, Object> htable = new Hashtable<Object, Object>();
		RecordSearch rs =new RecordSearch();		
		//sr =new SearchRecord(path);
		htable.clear();
		htable.put("mid", eventobject);
		rs.setConditionMap(htable);
		String line[] = rs.getArrayFromResultSet();
		htable.clear();
		for(int i=0;i<line.length;i++)
		{
			String splitline[] = line[i].split("\t");
			String value= splitline[Column.pv_index-1];
			if(value.equals("0"))
				value =  splitline[Column.vt_index-1];
			else
				value = gid.getItem(value);
			Sendmail.put(gid.getItem(splitline[Column.pid_index-1]), value);
		}
		attachment=Input.ROOT+Sendmail.get("attachment").toString()+tid+"_view"+Input.FILRFORMAT;
		File file =new File(attachment);
		if(file.exists()==true)
		{
			try 
			{
				htable.put("id",tid);
				rs.setConditionMap(htable);
				rs.setTablename("transaction");
				String line_tra_file []= rs.getArrayFromResultSet();
				Receiver re =new Receiver(eventobject,transaction_type,"Emailid");
				RECEIVERemailid = re.findReceiver(line_tra_file[0],tid);
				String UserEmail = getUserEmail(userId); 
				RECEIVERemailid.add(UserEmail);
				if(Sendmail.containsKey("query"))
				{
					Query query = new Query();
					query.initPool();
					query.setReportname("NameReport");
					query.initializeData();
					query.getResult();
					String buffer[]=query.getbuffer();
					for(int i=1;i<buffer.length;i++)
					{
						RECEIVERemailid.add(buffer[i]);
					}
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
			run();
		}
		else
			Result = false;
	}
	public void initializationData() 
	{
		gid = new GetIdName();
		REPORT = gid.getId(REPORT);
		TRANSTYPE =gid.getId(TRANSTYPE);
	}

	public boolean getResult() 
	{
		return Result;
		//return true; // THIS LINE ADD -> INTENET IS NOT WORKING 
	}
	String getUserEmail(String mobileNo)
	{
		try
		{
			String no = mobileNo;
			int mid_index=-1;
			int pv_index=-1;
			int vt_index =-1;
			mobileNo = gid.getId(mobileNo);
			String path = Input.MASTERREPORTSPATH + mobileNo + "//" +mobileNo +"_PV" + Input.FILRFORMAT;
			Hashtable<Object, Object> table = new Hashtable<Object, Object>();
			table.put("pv",mobileNo); 
			table.put("pid", gid.getId("mobileno"));
			SearchRecord sr = new SearchRecord(path);
			String [] result = sr.getRecordSet(table);
			if(result.length == 0)
			{
				path = Input.MASTERREPORTSPATH + no + "//" +no +"_VT" + Input.FILRFORMAT;
				table.remove("pv");
				table.put("vt",no);
				sr = new SearchRecord(path);
				result = sr.getRecordSet(table);
			}
			try 
			{
				mid_index = Column.mid_index-1;
				pv_index = Column.pv_index-1;
				vt_index = Column.vt_index-1;
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			String [] midResult = result[0].split("\t");
			String name = midResult[mid_index];
			path = Input.MASTERREPORTSPATH + name + "//" +name +"_mid" + Input.FILRFORMAT;
			table.clear();
			table.put("pid", gid.getId("emailid"));
			sr = new SearchRecord(path);
			String result1[] = sr.getRecordSet(table);
			midResult = result1[0].split("\t");
			name = midResult[pv_index];
			if(name.equals("0"))
			{
				name = midResult[vt_index];
			}
			else
				name = gid.getId(name); 
			return name;
		}
		catch (RuntimeException e) 
		{
			e.printStackTrace();
		}
		
		return " ";
	}

	public void SetData(String msg, String transaction_type, String tid, String userid) 
	{
		this.msg =msg;
		this.transaction_type=transaction_type;
		this.tid=tid;
		this.userId = userid;
	}

	public boolean afterAdd() 
	{
		return getResult();
	}

	public boolean afterDel() 
	{
		return getResult();
	}
	
	public boolean afterMod() 
	{
		return getResult();
	}

	public boolean afterView() 
	{
		return getResult();
	}
}
		